package edu.xmut.kakamusic.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.SeekBar;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.google.android.material.bottomsheet.BottomSheetDialog;

import java.util.List;
import java.util.Locale;
import java.util.Objects;

import edu.xmut.kakamusic.R;
import edu.xmut.kakamusic.activity.service.MusicPlayerService;
import edu.xmut.kakamusic.adapter.PlaylistAdapter;
import edu.xmut.kakamusic.bean.entity.Album;
import edu.xmut.kakamusic.bean.entity.Artist;
import edu.xmut.kakamusic.bean.entity.Music;
import edu.xmut.kakamusic.bean.form.MusicPlayForm;
import edu.xmut.kakamusic.databinding.ActivityMusicPlayerBinding;
import edu.xmut.kakamusic.utils.ApiResponse;
import edu.xmut.kakamusic.utils.Constants;
import edu.xmut.kakamusic.utils.IntentUtils;
import edu.xmut.kakamusic.utils.RequestUtils;
import edu.xmut.kakamusic.utils.SPUtils;
import edu.xmut.kakamusic.utils.ToastUtils;
import edu.xmut.kakamusic.utils.WindowUtils;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class MusicPlayerActivity extends AppCompatActivity {

    private LocalBroadcastManager localBroadcastManager;
    private edu.xmut.kakamusic.databinding.ActivityMusicPlayerBinding binding;
    private final static String TAG = MusicPlayerActivity.class.getSimpleName();

    private final Handler handler = new Handler(Looper.getMainLooper());

    private final Runnable updateSeekBar = new Runnable() {
        @Override
        public void run() {
            if (MusicPlayerService.isPlaying()) {
                // 获取当前播放进度
                int currentPosition = MusicPlayerService.getInstance().getCurrentPosition();
                // 获取总时长
                int duration = MusicPlayerService.getInstance().getDuration();
                // 更新进度条
                binding.progressBar.setMax(duration);
                binding.progressBar.setProgress(currentPosition);
                // 更新时间显示
                binding.currentTime.setText(formatTime(currentPosition));
                binding.totalTime.setText(formatTime(duration));
            }
            // 每秒执行一次
            handler.postDelayed(this, 1000);
        }
    };

    // 格式化时间
    private String formatTime(int milliseconds) {
        int seconds = milliseconds / 1000;
        int minutes = seconds / 60;
        seconds = seconds % 60;
        return String.format(Locale.getDefault(), "%02d:%02d", minutes, seconds);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // 隐藏actionBar
        WindowUtils.hideActionBar(this);
        // 开启透明色状态栏
        EdgeToEdge.enable(this);
        super.onCreate(savedInstanceState);
        binding = ActivityMusicPlayerBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        // 设置状态栏背景色
        WindowUtils.setStatusBarColor(this, Color.TRANSPARENT);
        // 设置状态栏的外观
        WindowUtils.setLightStatusBarAppearance(this, false);
        // 适配沉浸式导航栏和状态栏
        adaptNavigationAndStatusBar();
        // 获取本地广播管理器
        localBroadcastManager = LocalBroadcastManager.getInstance(this);
        // 启动音乐服务
        startMusicService();
        // 绑定视图
        initView();
        // 处理事件
        handleEvent();
        // 获取音乐数据并播放
        getMusicDataAndPlay();
        // 初始化进度条
        initSeekBar();
    }

    private void adaptNavigationAndStatusBar() {
        LinearLayout toolbar = binding.topToolbar;
        ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) toolbar.getLayoutParams();
        params.topMargin = WindowUtils.getStatusBarHeight(this);
        toolbar.setLayoutParams(params);
        LinearLayout bottomControlBar = binding.bottomControlBar;
        ViewGroup.MarginLayoutParams params1 = (ViewGroup.MarginLayoutParams) bottomControlBar.getLayoutParams();
        params1.bottomMargin = WindowUtils.getNavigationBarHeight(this);
        bottomControlBar.setLayoutParams(params1);
    }

    private void initView() {
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Constants.MUSIC_START_PLAY_SERVICE);
        intentFilter.addAction(Constants.MUSIC_DATA);
        localBroadcastManager.registerReceiver(new LocalReceiver(), intentFilter);
        updatePlayModeButton(); // 初始化播放模式按钮状态
    }

    private void setPlayerInfo(Music music) {
        Album album = music.getAlbum();
        Artist artist = music.getArtist();
        binding.artistName.setText(artist.getName());
        binding.musicTitle.setText(music.getName());
        Glide.with(getBaseContext())
                .load(album.getPicUrl())
                .into(binding.albumCover);
    }

    class LocalReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            switch (Objects.requireNonNull(action)) {
                case Constants.MUSIC_START_PLAY_SERVICE:
                case Constants.MUSIC_DATA:
                    Music music = (Music) intent.getSerializableExtra(Constants.MUSIC_DATA);
                    setPlayerInfo(music);
                    updatePlayPauseButton(MusicPlayerService.isPlaying());
                    break;
                default:
                    break;
            }
        }
    }

    private void handleEvent() {
        binding.playOrPauseButton.setOnClickListener(v -> {
            switch (MusicPlayerService.getMediaPlayerState()) {
                case Constants.PAUSE_STATUS:
                    localBroadcastManager.sendBroadcast(IntentUtils.createIntent(Constants.PLAY));
                    updatePlayPauseButton(true);
                    break;
                case Constants.PLAYING_STATUS:
                    localBroadcastManager.sendBroadcast(IntentUtils.createIntent(Constants.PAUSE));
                    updatePlayPauseButton(false);
                    break;
                default:
                    break;
            }
        });

        // 添加上一首按钮事件
        binding.previousButton.setOnClickListener(v -> {
            localBroadcastManager.sendBroadcast(IntentUtils.createIntent(Constants.PREVIOUS));
        });

        // 添加下一首按钮事件
        binding.nextButton.setOnClickListener(v -> {
            localBroadcastManager.sendBroadcast(IntentUtils.createIntent(Constants.NEXT));
        });

        // 处理返回按钮
        binding.cancel.setOnClickListener(v -> {
            finish();
            // 应用退出动画
            overridePendingTransition(0, R.anim.slide_out_bottom);
        });

        // 添加播放模式切换按钮事件
        binding.playMode.setOnClickListener(v -> {
            int currentMode = MusicPlayerService.getPlayMode();
            int newMode;
            switch (currentMode) {
                case Constants.PLAY_MODE_SEQUENCE:
                    newMode = Constants.PLAY_MODE_RANDOM;
                    ToastUtils.show(this, "随机播放");
                    break;
                case Constants.PLAY_MODE_RANDOM:
                    newMode = Constants.PLAY_MODE_SINGLE;
                    ToastUtils.show(this, "单曲循环");
                    break;
                case Constants.PLAY_MODE_SINGLE:
                default:
                    newMode = Constants.PLAY_MODE_SEQUENCE;
                    ToastUtils.show(this, "顺序播放");
                    break;
            }
            MusicPlayerService.setPlayMode(newMode);
            updatePlayModeButton();
        });

        // 添加播放列表按钮点击事件
        binding.playlistButton.setOnClickListener(v -> {
            showPlaylistDialog();
        });
    }

    private void getMusicDataAndPlay() {
        MusicPlayForm musicPlayForm = (MusicPlayForm) getIntent().getSerializableExtra(Constants.MUSIC_PLAY_REQUEST);
        SPUtils spUtils = new SPUtils(getBaseContext());
        String token = spUtils.getString("token");
        RequestUtils.getInstance().getMusicCallable(token, musicPlayForm)
                .enqueue(new Callback<ApiResponse<Music>>() {
                    @Override
                    public void onResponse(Call<ApiResponse<Music>> call, Response<ApiResponse<Music>> response) {
                        if (Objects.equals(response.code(), 200)) {
                            ApiResponse<Music> apiResponse = response.body();
                            if (Objects.nonNull(apiResponse) && Objects.equals(apiResponse.getCode(), 200)) {
                                Music music = apiResponse.getData();
                                Intent intentWithData = IntentUtils.createIntentWithData(Constants.PLAY, Constants.MUSIC_DATA, music);
                                localBroadcastManager.sendBroadcast(intentWithData);
                            } else {
                                ToastUtils.show(getBaseContext(), apiResponse.getMessage());
                            }
                        } else {
                            int code = response.code();
                            ToastUtils.show(getBaseContext(), "网络错误，状态码: " + code);
                        }
                    }

                    @Override
                    public void onFailure(Call<ApiResponse<Music>> call, Throwable t) {
                        ToastUtils.show(getBaseContext(), "网络错误" + t.getMessage());
                        Log.d(TAG, "getPlaySong: " + t.getMessage());
                    }
                });
    }

    private void startMusicService() {
        // 如果音乐服务没启动，才启动音乐服务
        if (!MusicPlayerService.isRunning()) {
            Intent intent = new Intent(this, MusicPlayerService.class);
            startService(intent);
        }
        // 向音乐服务获取播放音乐的信息
        localBroadcastManager.sendBroadcast(IntentUtils.createIntent(Constants.GET_MUSIC_DATA));
    }

    private void initSeekBar() {
        // 设置进度条变化监听
        binding.progressBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (fromUser) {
                    // 用户拖动进度条时更新时间显示
                    binding.currentTime.setText(formatTime(progress));
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                // 开始拖动时暂停更新
                handler.removeCallbacks(updateSeekBar);
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                // 停止拖动时设置播放位置
                if (MusicPlayerService.getInstance() != null) {
                    MusicPlayerService.getInstance().seekTo(seekBar.getProgress());
                }
                // 恢复更新
                handler.post(updateSeekBar);
            }
        });

        // 开始更新进度
        handler.post(updateSeekBar);
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.d(TAG, "onResume: MusicPlayerActivity继续");
        // 恢复更新
        handler.post(updateSeekBar);
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.d(TAG, "onPause: MusicPlayerActivity暂停");
        // 暂停更新
        handler.removeCallbacks(updateSeekBar);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "onDestroy: MusicPlayerActivity销毁");
        // 停止更新
        handler.removeCallbacks(updateSeekBar);
    }

    private void updatePlayPauseButton(boolean isPlaying) {
        if (isPlaying) {
            binding.playOrPauseButton.setImageResource(R.drawable.ic_pause);
        } else {
            binding.playOrPauseButton.setImageResource(R.drawable.ic_play);
        }
    }

    private void updatePlayModeButton() {
        switch (MusicPlayerService.getPlayMode()) {
            case Constants.PLAY_MODE_RANDOM:
                binding.playMode.setImageResource(R.drawable.ic_shuffle);
                break;
            case Constants.PLAY_MODE_SINGLE:
                binding.playMode.setImageResource(R.drawable.ic_repeat_one);
                break;
            case Constants.PLAY_MODE_SEQUENCE:
            default:
                binding.playMode.setImageResource(R.drawable.ic_repeat);
                break;
        }
    }

    // 重写返回键处理
    @Override
    public void onBackPressed() {
        super.onBackPressed();
        // 应用退出动画
        overridePendingTransition(0, R.anim.slide_out_bottom);
    }

    private void showPlaylistDialog() {
        BottomSheetDialog dialog = new BottomSheetDialog(this);
        View view = getLayoutInflater().inflate(R.layout.dialog_playlist, null);
        RecyclerView recyclerView = view.findViewById(R.id.playlist_recycler_view);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));

        List<Music> playQueue = MusicPlayerService.getInstance().getPlayQueue();
        PlaylistAdapter adapter = new PlaylistAdapter(playQueue);
        recyclerView.setAdapter(adapter);

        adapter.setOnItemClickListener(new PlaylistAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                MusicPlayerService.getInstance().playAtPosition(position);
                dialog.dismiss();
            }

            @Override
            public void onDeleteClick(int position) {
                MusicPlayerService.getInstance().removeFromQueue(position);
                adapter.notifyItemRemoved(position);
                if (playQueue.isEmpty()) {
                    dialog.dismiss();
                }
            }
        });

        dialog.setContentView(view);
        dialog.show();
    }
}